package com.atguigu.daijia.customer.service.impl;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.mapper.CustomerInfoMapper;
import com.atguigu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.atguigu.daijia.customer.service.CustomerInfoService;
import com.atguigu.daijia.model.entity.customer.CustomerInfo;
import com.atguigu.daijia.model.entity.customer.CustomerLoginLog;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    private final WxMaService wxMaService;

    private final CustomerLoginLogMapper customerLoginLogMapper;

    /**
     * 微信小程序用户登录接口，处理用户登录流程并返回用户ID
     *
     * @param code 微信小程序登录时获取的临时登录凭证
     * @return 用户ID
     * @throws GuiguException 当登录过程中出现异常时抛出业务异常
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public Long login(String code) {
        // 校验输入的code是否为空，防止空值导致后续流程异常
        if (StringUtils.isEmpty(code)) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        String openId;
        try {
            // 调用微信服务，使用临时登录凭证code换取用户唯一标识openId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openId = sessionInfo.getOpenid();
            log.info("【小程序授权】openId={}", openId);
        } catch (WxErrorException e) {
            // 处理微信接口调用异常，记录错误日志并抛出业务异常
            log.error("微信登录获取openId失败", e);
            throw new GuiguException(ResultCodeEnum.WX_CODE_ERROR);
        } catch (Exception e) {
            // 处理未知异常，确保系统稳定性
            log.error("微信登录未知异常", e);
            throw new GuiguException(ResultCodeEnum.SERVICE_ERROR);
        }

        // 根据openId查询用户信息，判断用户是否已存在
        CustomerInfo customerInfo = this.getOne(
                new LambdaQueryWrapper<CustomerInfo>()
                        .eq(CustomerInfo::getWxOpenId, openId)
        );

        // 处理新用户首次登录的情况
        if (customerInfo == null) {
            customerInfo = new CustomerInfo();

            // 生成临时昵称，使用时间戳确保唯一性
            customerInfo.setNickname("用户_" + System.currentTimeMillis());

            // 设置默认头像
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            customerInfo.setWxOpenId(openId);

            // 设置用户状态为已激活
            customerInfo.setStatus(1);

            // 保存新用户信息到数据库，若保存失败则抛出异常
            if (!this.save(customerInfo)) {
                throw new GuiguException(ResultCodeEnum.FAIL);
            }
        }

        // 记录用户登录日志，便于后续分析和审计
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();

        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");

        customerLoginLogMapper.insert(customerLoginLog);

        // 返回用户ID给调用方
        return customerInfo.getId();
    }

    /**
     * 获取客户登录信息
     */
    @Override
    public CustomerLoginVo getCustomerLoginInfo(Long customerId) {
        CustomerInfo customerInfo = this.getById(customerId);
        CustomerLoginVo customerInfoVo = new CustomerLoginVo();
        BeanUtils.copyProperties(customerInfo, customerInfoVo);

        // 判断是否绑定手机号码，如果未绑定，小程序端发起绑定事件
        Boolean isBindPhone = StringUtils.hasText(customerInfo.getPhone());
        customerInfoVo.setIsBindPhone(isBindPhone);
        return customerInfoVo;
    }
}
